
<!-- 这是master 原有的tree 为了解决M3环境的问题  使用了test分支的tree -->
<template>
  <view class="tki-tree">
    <view class="tki-tree-view">
      <block v-for="(item, index) in treeList" :key="index">
        <view
          class="tki-tree-item"
          :style="[{ paddingLeft: item.rank * 15 + 'px' }]"
          :class="{
            border: border === true,
            show: item.show,
            last: item.lastRank,
            showchild: item.showChild,
            open: item.open,
          }"
        >
          <view class="tki-tree-label" :class="'tki-tree-label' + index">
            <u-icon :name="item.showChild ? currentIcon : defaultIcon" style="margin-right: 20rpx" @click="_treeItemTap(item, index)"></u-icon>
            <image v-if="index > 0" class="fileImage" src="../../static/images/fileManage/file_manage_list.svg"></image>
            <view class="fileTitle">{{ item.chapterName }}</view>
            <view class="moreClass">
                <!--              <uni-icons type="more-filled" class="uni_icon" size="20" @click="openMore(index)"></uni-icons>-->
                <view  :tabindex="index"
                       @click="handleFocus(index)"  @focus="handleFocus(index)" @blur="handleBlur(index)" class="handleInput"
                       :class="index === operationIndex?'active':''"></view>
                <view class="videoOperation" ref="operation" v-if="index === operationIndex">
                    <view class="videoOperationBtn" @click="add(item, index)" v-if="item.rank < 2">添加章/节</view>
                    <view class="videoOperationBtn" @click="editName(item, index)" v-if="item.rank !== 0">重命名</view>
                    <view class="videoOperationBtn" @click="uploadVideo(item, 'video')">导入视频</view>
                    <view class="videoOperationBtn" @click="uploadVideo(item, 'ppt')">导入课件</view>
                    <view class="videoOperationBtn" @click="delFn(item)" v-if="item.rank !== 0">删除</view>
                </view>
            </view>
          </view>
          <view v-if="item.showChild && item.show && item.open">
            <view class="tki-tree-label tki-tree-label-file" v-for="(videoItem, videoIndex) in item.videoList" :key="'videoItem' + videoIndex">
              <view class="fileTitle" @click="handlePlayer(videoItem)"
                >{{ videoItem.fileName }}
                <view class="round" :class="videoItem.status == 2 ? 'red' : videoItem.status == 5 ? 'blue' : 'orange'"></view>
              </view>
    
                <view class="moreClass">
                    <!--                <uni-icons type="more-filled" class="uni_icon" size="20" @click="openDel(videoIndex, index)"></uni-icons>-->
                    <input type="button" disabled :tabindex="1000 + videoIndex"
                           @click="delFocus(index)"  @focus="delFocus(videoIndex, index)" @blur="delBlur(videoIndex, index)"
                           class="handleInput" :class="index === operationVideoIndex?'active':''">
                    <!-- 判断除新增外需要调用后台按钮权限操作 -->
                    <view class="videoOperation" ref="videoOperation"
                          v-if="videoItem.permissionVo && videoIndex === operationVideoIndex && operationParentIndex === index">
                        <view class="videoOperationBtn" v-if="videoItem.permissionVo.submit && isEdit"
                              @click="submit(videoItem)">提交
                        </view>
                        <view class="videoOperationBtn" v-if="videoItem.permissionVo.withdraw && isEdit"
                              @click="withdraw(videoItem)">撤回
                        </view>
                        <view class="videoOperationBtn" v-if="videoItem.permissionVo.update && isEdit"
                              @click="update(item, videoItem)">更新
                        </view>
                        <view class="videoOperationBtn" v-if="videoItem.permissionVo.delete"
                              @click="handleDel(videoItem)">删除
                        </view>
                        <view class="videoOperationBtn" @click="handleFileInfo(videoItem)">文件信息</view>
                        <view class="videoOperationBtn" v-if="videoItem.permissionVo.rejectInfo"
                              @click="rejectInfoFn(videoItem)">驳回原因
                        </view>
                    </view>
                    <!-- 新增得有删除按钮 -->
                <view class="videoOperation" ref="videoOperation" v-if="!videoItem.permissionVo && videoIndex === operationVideoIndex && operationParentIndex === index">
                  <view class="videoOperationBtn" @click="handleDel(videoItem)">删除</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </block>
    </view>
    <!-- 文件上传弹框 -->
    <u-popup :show="showTree" @close="closePopup" :round="10" mode="bottom">
      <view class="add_chapter_popup">
        <view class="title">第{{ titleIndex }}{{ titleLabel }}</view>
        <view class="upload_type">
          <text>{{ titleLabel }}名称:</text>
          <u-input @change="inputChange" :placeholder="this.titleLabel === '章' ? '请输入章名称' : '请输入节名称'" clearable v-model="formData.folderName"></u-input>
        </view>
        <!-- 				<view class="upload_type">
                    <text>作者名称:</text>
                    <u--input placeholder="请输入作者名称" clearable v-model="formData.author"></u--input>
                </view>
                <view class="upload_type" style="margin-top: 50rpx;">
                    <text>课程简介:</text>
                    <u--textarea v-model="formData.synopsis" placeholder="请输入课程简介" count></u--textarea>
                </view> -->
        <view class="bottom">
          <u-button text="取消" @click="closePopup"></u-button>
          <u-button type="primary" :disabled="!formData.folderName" text="确定" @click="sureFn"></u-button>
        </view>
      </view>
    </u-popup>
    <!-- 驳回 -->
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog cancelText="关闭" confirmText="确定" title="驳回原因" :content="reasonInfo">
        <textarea :disabled="isEdit" v-model="reasonInfo" placeholder="请输入驳回原因" style="width: 100%; min-height: 70rpx !important"></textarea>
      </uni-popup-dialog>
    </uni-popup>
    <!-- 模态框 -->
    <u-modal title="更新" content="原文件已入库,如需更新,需对原文件进行升版" showCancelButton :show="updateModel" @cancel="closeModel" @confirm="confirm" ref="uModal" :asyncClose="true"> </u-modal>
  </view>
</template>

<script>
const baseUrl = config.baseUrl
import uploadView from '../../pages/uploadView'
export default {
  name: "tree",
  components: {uploadView},
  props: {
    range: {
      type: Array,
      default: function () {
        return [];
      },
    },
    idKey: {
      type: String,
      default: "id",
    },
    rangeKey: {
      type: String,
      default: "label",
    },
    title: {
      type: String,
      default: "",
    },
    multiple: {
      // 是否可以多选
      type: Boolean,
      default: false,
      // default: true
    },
    selectParent: {
      //是否可以选父级
      type: Boolean,
      default: false,
    },
    foldAll: {
      //折叠时关闭所有已经打开的子集，再次打开时需要一级一级打开
      type: Boolean,
      default: false,
    },
    confirmColor: {
      // 确定按钮颜色
      type: String,
      default: "", // #07bb07
    },
    cancelColor: {
      // 取消按钮颜色
      type: String,
      default: "", // #757575
    },
    titleColor: {
      // 标题颜色
      type: String,
      default: "", // #757575
    },
    currentIcon: {
      type: String,
      default: "arrow-down",
    },
    defaultIcon: {
      type: String,
      default: "arrow-right",
    },
    lastIcon: {
      type: String,
      default: "",
    },
    border: {
      //是否有分割线
      type: Boolean,
      default: false,
    },
    isEdit: {
      //是否为编辑时调用
      type: Boolean,
      default: false,
    },
    methods: {
      type: String,
      default: "",
    }
  
  },
  data() {
    return {
      showTree: false,
      treeList: [],
      selectIndex: -1,
      operationIndex: -1,
      operationVideoIndex: -1,
      operationParentIndex: -1,
      show: false,
      formData: {
        folderName: "",
        author: "",
        synopsis: "",
      },
      titleIndex: 1,
      titleLabel: "章",
      parentId: null,
      isEditName: false,
      oldChapterName: "",
      reasonInfo: "",
      updateModel: false,
      updateItem:null
    };
  },
  computed: {},
  methods: {
    uploadVideo(row, fileType) {
      this.operationIndex = -1;
      this.$emit("uploadVideo", row, fileType);
    },
    add(item, index) {
      this.isEditName = false;
      this.operationIndex = -1;
      this.showTree = true;
      this.titleIndex = item.source.children ? item.source.children.length + 1 : 1;
      this.titleLabel = item.rank === 0 ? "章" : "节";
      this.formData.folderName = "第" + this.titleIndex + this.titleLabel;
      this.parentId = item.id;
    },
    // 修改名称
    editName(item, index) {
      console.log(item, "fff");
      this.isEditName = true;
      this.operationIndex = -1;
      this.showTree = true;
      this.titleIndex = item.source.children ? item.source.children.length + 1 : 1;
      this.titleLabel = item.rank === 1 ? "章" : "节";
      this.formData.folderName = item.chapterName;
      this.parentId = item.id;

      // 需要保存被修改前的名称，如果取消将替换旧数据
      // this.oldChapterName = item.chapterName;
    },
    handlePlayer(row) {
      this.operationVideoIndex = -1;
      this.$emit("handlePlayer", row);
    },
    // 提交
    submit(item) {
      let that = this;
      uni.showModal({
        title: "提示",
        content: "确认提交该数据吗？",
        success: function (res) {
          if (res.confirm) {
            that
              .$request({
                url: "/knowledgeFile/file/submit",
                method: "post",
                data: {
                  id: item.id,
                },
              })
              .then(({ data }) => {
                that.$modal.loading("提交成功！");
                setTimeout(() => {
                  that.$modal.closeLoading();
                  that.$router.go(0);
                }, 1000);
              });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    // 撤回
    withdraw(item) {
      let that = this;
      uni.showModal({
        title: "提示",
        content: "确认撤回该数据吗？",
        success: function (res) {
          if (res.confirm) {
            that
              .$request({
                url: "/knowledgeFile/file/withdraw",
                method: "post",
                data: {
                  id: item.id,
                },
              })
              .then(({ data }) => {
                that.$modal.loading("撤回成功！");
                setTimeout(() => {
                  that.$modal.closeLoading();
                  that.$router.go(0);
                }, 1000);
              });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    // 更新
    update(parentRow, row) {
      this.operationIndex = -1;
      if (row && row.status == 5) {
        // 模态框提示
        this.updateModel = true;
        this.updateItem={
          parentRow,
          row
        }
        return;
      }
      this.$emit("handleUpdate", parentRow, row);
    },
    confirm() {
      const { parentRow, row } = this.updateItem
      this.$emit("handleUpdate", parentRow, row);
      this.updateModel = false;
    },
    closeModel() {
      this.updateModel = false;
    },
    delFn(item) {
      let that = this;
      that.operationIndex = -1;
      uni.showModal({
        title: "提示",
        content: "确认删除该数据吗？",
        success: function (res) {
          if (res.confirm) {
            that.$emit("del", item.id);
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
      openMore(index) {
          this.operationVideoIndex = -1
          this.operationIndex = index
          this.operationParentIndex = -1
          setTimeout(() => {
              this.operationIndex = -1
          }, 3000)
      },
    
      handleFocus(index) {
          setTimeout(() => {
              this.operationVideoIndex = -1
              this.operationIndex = index
              this.operationParentIndex = -1
          }, 50)
      },
      handleBlur(index) {
          setTimeout(() => {
              this.operationIndex = -1
          }, 50)
      },
      openDel(videoIndex, index) {
          this.operationIndex = -1
          this.operationVideoIndex = videoIndex
          this.operationParentIndex = index
          setTimeout(() => {
              this.operationVideoIndex = -1
              this.operationParentIndex = -1
          }, 3000)
      },
    
      delFocus(videoIndex, index) {
          setTimeout(() => {
              this.operationIndex = -1
              this.operationVideoIndex = videoIndex
              this.operationParentIndex = index
          }, 50)
      },
      delBlur(videoIndex, index) {
          setTimeout(() => {
              this.operationVideoIndex = -1
              this.operationParentIndex = -1
          }, 50)
      },
      inputChange(e) {
          // const result = this.treeList.find( item => item.id == this.parentId)
          // console.log(e,this.titleIndex,this.treeList,result,"打印input")
          // result.chapterName = e
      },
      sureFn() {
          //修改名称
          if (this.isEditName) {
              this.showTree = false
              console.log(this.formData)
        this.$emit("editName", this.formData, this.parentId);
        return;
      }
      // 新增
      const item = {
        chapterName: this.formData.folderName,
        id: Date.now(),
        isEdit: this.isEdit,
        chapter: Date.now(),
        parentId: this.parentId,
      };
      this.showTree = false;
      console.log("增加parentid", item, this.parentId);
      this.$emit("confirm", item, this.parentId);
    },
    closePopup() {
      this.showTree = false;
    },
    _show() {
      this.showTree = true;
    },
    _hide() {
      this.showTree = false;
    },
    _confirm() {
      // 处理所选数据
      let rt = [],
        obj = {};
      this.treeList.forEach((v, i) => {
        if (this.treeList[i].checked) {
          obj = {};
          obj.parents = this.treeList[i].parents;
          obj = Object.assign(obj, this.treeList[i].source);
          // 移除子元素
          delete obj.children;
          rt.push(obj);
        }
      });
      this._hide();
      this.$emit("confirm", rt);
    },
    //扁平化树结构
    _renderTreeList(list = [], rank = 0, parentId = [], parents = []) {
      list.forEach((item) => {
        this.treeList.push({
          id: item[this.idKey],
          chapter: item[this.idKey] || Date.now(),
          chapterName: item[this.rangeKey],
          source: item,
          parentId, // 父级id数组
          parents, // 父级id数组
          rank, // 层级
          showChild: true, //子级是否显示
          open: true, //是否打开
          show: true, // 自身是否显示
          hideArr: [],
          orChecked: item.checked || false,
          checked: item.checked || false,
          videoList: item.videoList,
        });
        if (Array.isArray(item.children) && item.children.length > 0) {
          let parentid = [...parentId],
            parentArr = [...parents],
            childrenid = [...childrenid];
          delete parentArr.children;
          parentid.push(item[this.idKey]);
          parentArr.push({
            [this.idKey]: item[this.idKey],
            [this.rangeKey]: item[this.rangeKey],
          });
          this._renderTreeList(item.children, rank + 1, parentid, parentArr);
        } else {
          this.treeList[this.treeList.length - 1].lastRank = true;
        }
      });
    },
    // 处理默认选择
    _defaultSelect() {
      this.treeList.forEach((v, i) => {
        if (v.checked) {
          this.treeList.forEach((v2, i2) => {
            if (v.parentId.toString().indexOf(v2.parentId.toString()) >= 0) {
              v2.show = true;
              if (v.parentId.includes(v2.id)) {
                v2.showChild = true;
                v2.open = true;
              }
            }
          });
        }
      });
    },
    // 点击
    _treeItemTap(item, index) {
      /*if (item.lastRank === true) {
        //点击最后一级时触发事件
        this.treeList[index].checked = !this.treeList[index].checked;
        this._fixMultiple(index);
        return;
      }*/
      let list = this.treeList;
      let id = item.id;
      item.showChild = !item.showChild;
      item.open = item.showChild ? true : !item.open;
      list.forEach((childItem, i) => {
        if (item.showChild === false) {
          //隐藏所有子级
          if (!childItem.parentId.includes(id)) {
            return;
          }
          if (!this.foldAll) {
            if (childItem.lastRank !== true && !childItem.open) {
              childItem.showChild = false;
            }
            // 为隐藏的内容添加一个标记
            if (childItem.show) {
              childItem.hideArr[item.rank] = id;
            }
          } else {
            if (childItem.lastRank !== true) {
              childItem.showChild = false;
            }
          }
          childItem.show = false;
        } else {
          // 打开子集
          if (childItem.parentId[childItem.parentId.length - 1] === id) {
            childItem.show = true;
          }
          // 打开被隐藏的子集
          if (childItem.parentId.includes(id) && !this.foldAll) {
            if (childItem.hideArr[item.rank] === id) {
              childItem.show = true;
              if (childItem.open && childItem.showChild) {
                childItem.showChild = true;
              } else {
                childItem.showChild = false;
              }
              childItem.hideArr[item.rank] = null;
            }
          }
        }
      });
    },
    // 处理单选多选
    _fixMultiple(index) {
      if (!this.multiple) {
        // 如果是单选
        this.treeList.forEach((v, i) => {
          if (i !== index) {
            this.treeList[i].checked = false;
          } else {
            this.treeList[i].checked = true;
          }
        });
      }
    },
    // 重置数据
    _reTreeList() {
      this.treeList.forEach((v, i) => {
        this.treeList[i].checked = v.orChecked;
      });
    },
    _initTree(range = this.range) {
      this.treeList = [];
      this._renderTreeList(range);
      /*this.$nextTick(() => {
				    this._defaultSelect(range)
				})*/
    },
    handleFileInfo(row) {
      this.operationVideoIndex = -1;
      console.log(8989, row);
      this.$emit("handleFileInfo", row);
    },

    // 查看驳回原因
    rejectInfoFn(item) {
      console.log("ffff", item);
      this.reasonInfo = item.reason;
      this.$refs.alertDialog.open();
    },
    handleDel(row) {
      console.log("tree.vue===>", row);
      this.operationVideoIndex = -1;
      let that = this;
      uni.showModal({
        title: "提示",
        content: "确认删除该文件吗？",
        success: function (res) {
          if (res.confirm) {
            that.$emit("handleDel", row);
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
  },
  watch: {
    range(list) {
      this._initTree(list);
    },
    multiple() {
      if (this.range.length) {
        this._reTreeList();
      }
    },
    selectParent() {
      if (this.range.length) {
        this._reTreeList();
      }
    },
  },
  mounted() {
    this._initTree();
    if (this.isEdit) {
      uni.setNavigationBarTitle({
        title: "文件更新",
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.tki-tree-mask {
  position: fixed;
  top: 0rpx;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  z-index: 9998;
  background-color: rgba(0, 0, 0, 0.6);
  //opacity: 0;
  display: none;
  transition: all 0.3s ease;
  visibility: hidden;
}

.tki-tree-mask.show {
  visibility: visible;
  //opacity: 1;
  display: block;
}

.tki-tree-cnt {
  position: fixed;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  z-index: 9999;
  top: 160rpx;
  transition: all 0.3s ease;
  transform: translateY(100%);
}

.tki-tree-cnt.show {
  transform: translateY(0);
}

.tki-tree-bar {
  background-color: #fff;
  height: 72rpx;
  padding-left: 20rpx;
  padding-right: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  border-bottom-width: 1rpx !important;
  border-bottom-style: solid;
  border-bottom-color: #f5f5f5;
  font-size: 32rpx;
  color: #757575;
  line-height: 1;
}

.tki-tree-bar-confirm {
  color: #07bb07;
}

.tki-tree-view {
  padding: 20rpx 0;
}

.tki-tree-item {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
  font-size: 26rpx;
  color: #757575;
  line-height: 1;
  width: 100%;
  //opacity: 0;
  display: none;
  transition: 0.2s;
  position: relative;
  // overflow: hidden;
  &.show {
    display: block;
  }
  &.showchild:before {
    transform: rotate(90deg);
  }
  &.last {
    &:before {
      //opacity: 0;
      display: none;
    }
  }
}
.tki-tree-icon {
  width: 26rpx;
  height: 26rpx;
  margin-right: 8rpx;
}

.tki-tree-label {
  flex: 1;
  display: flex;
  align-items: center;
  height: 100%;
  width: 100%;
  line-height: 1.2;
  padding: 0 30rpx 0 20rpx;
  &.tki-tree-label0 {
    background: #f4f6f9;
  }
  .moreClass {
    margin: 0 0 0 auto;
    position: relative;
    .uni_icon {
      &:hover {
        color: #0084ff !important;
      }
    }
  }
  .u-icon__icon {
    color: #4c5a67 !important;
  }
  .fileImage {
    width: 24rpx;
    height: 24rpx;
    margin-right: 28rpx;
  }
  .fileTitle {
    width: calc(100% - 60rpx);
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    height: 72rpx;
    line-height: 72rpx;
    font-family: 思源黑体;
    font-size: 30rpx;
    color: #1c2126;
  }
  &.tki-tree-label-file {
    padding-left: 100rpx;
    box-sizing: border-box;
  }
}

.tki-tree-check {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.tki-tree-check-yes,
.tki-tree-check-no {
  width: 20px;
  height: 20px;
  border-top-left-radius: 20%;
  border-top-right-radius: 20%;
  border-bottom-right-radius: 20%;
  border-bottom-left-radius: 20%;
  border-top-width: 1rpx;
  border-left-width: 1rpx;
  border-bottom-width: 1rpx;
  border-right-width: 1rpx;
  border-style: solid;
  border-color: #07bb07;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}

.tki-tree-check-yes-b {
  width: 12px;
  height: 12px;
  border-top-left-radius: 20%;
  border-top-right-radius: 20%;
  border-bottom-right-radius: 20%;
  border-bottom-left-radius: 20%;
  background-color: #07bb07;
}

.tki-tree-check .radio {
  border-top-left-radius: 50%;
  border-top-right-radius: 50%;
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
}

.tki-tree-check .radio .tki-tree-check-yes-b {
  border-top-left-radius: 50%;
  border-top-right-radius: 50%;
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
}

.hover-c {
  opacity: 0.6;
}

.videoOperation {
  width: 172rpx !important;
  background: #ffffff;
  box-shadow: 0 2rpx 8rpx 0 rgba(170, 190, 206, 0.4);
  position: absolute;
  right: 10rpx;
  margin-top: -10rpx;
  z-index: 99;
  .videoOperationBtn {
    width: 100%;
    text-align: center;
    height: 68rpx;
    line-height: 68rpx;
    font-family: 思源黑体;
    font-size: 30rpx;
    color: #1c2126;
    &:hover {
      background: #f4f6f9 !important;
    }
  }
}

.add_chapter_popup {
  padding: 40rpx;
  font-family: Poppins;
  font-size: 32rpx;
  .upload_type {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100rpx;
    gap: 30rpx;
  }

  .bottom {
    width: 100%;
    display: flex;
    justify-content: space-between;
    height: 80rpx;
    padding: 0 30rpx;
    border-radius: 16px;
    ::v-deep .u-button {
      width: 100%;
      font-family: Poppins;
      font-size: 32rpx;
      height: 80rpx;
      & + .u-button {
        margin-left: 30rpx;
      }
    }
  }
}
.round {
  width: 20rpx;
  height: 20rpx;
  display: inline-block;
  margin-left: 24rpx;
}

.orange {
  background: #f9d548;
  box-shadow: 0px 0px 4px 0px rgba(249, 213, 72, 0.4);
}

.red {
  background: #f53f3f;
  box-shadow: 0px 0px 4px 0px rgba(245, 63, 63, 0.4);
}

.blue {
  background: #0084ff;
  box-shadow: 0px 0px 4px 0px rgba(0, 132, 255, 0.4);
}
::v-deep uni-textarea {
  min-height: 60rpx !important;
  height: auto !important;
}
</style>
